package com.paco.study.cloud.email.service.impl;

import com.paco.study.cloud.email.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.from}")
    private String from;

    @Override
    public boolean send(String email, String code) {

        return sendSimpleMail(email, code);
    }

    public boolean sendSimpleMail(String email, String code) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(from);
            simpleMailMessage.setTo(email);
            simpleMailMessage.setSubject("验证码");
            simpleMailMessage.setText("你的验证码是:" + code);
//            异步发送
            new Thread(() -> javaMailSender.send(simpleMailMessage)).start();
            log.info("send success:{}[{}]", email, code);
            return true;
        } catch (Exception e) {
            log.error("发送失败:{}", e.getMessage());
            return false;
        }
    }
}
